package com.weitu.contractor.controller;

import com.weitu.base.annotaion.SystemLog;
import com.weitu.base.controller.BaseController;
import com.weitu.contractor.entity.ContractorStaff;
import com.weitu.contractor.entity.ContractorStaffCriteria;
import com.weitu.contractor.service.ContractorInfoService;
import com.weitu.contractor.service.ContractorStaffService;
import com.weitu.contractor.service.impl.ContractorInfoServiceImpl;
import com.weitu.paging.DataGridPagination;
import com.weitu.permission.dataAuthority.service.DataAuthorityService;
import com.weitu.plugin.PageView;
import com.weitu.util.AjaxResult;
import com.weitu.util.DateTimeUtil;
import com.weitu.util.IDGenerator;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.weitu.util.AjaxResult.fail;
import static com.weitu.util.AjaxResult.success;

/**
 * @author LiMeng 2017/4/14
 */
@Controller
@RequestMapping(value = "contractor/contractorStaff")
public class ContractorStaffController extends BaseController {
    private static final String MODULE_BATH_PATH = BASE_JSP_PATH + "contractor/contractorStaff";
    private static final Logger logger = LoggerFactory.getLogger(ContractorInfoServiceImpl.class);
    private final ContractorStaffService contractorStaffService;
    private final ContractorInfoService contractorInfoService;
    private final DataAuthorityService dataAuthorityService;

    @Autowired
    public ContractorStaffController(ContractorStaffService contractorStaffService
            , ContractorInfoService contractorInfoService
            , DataAuthorityService dataAuthorityService) {
        this.contractorStaffService = contractorStaffService;
        this.contractorInfoService = contractorInfoService;
        this.dataAuthorityService = dataAuthorityService;
    }


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list() {
        return MODULE_BATH_PATH + "/list";
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    public Object listAjax(HttpServletRequest request, String sort) throws Exception {
        ContractorStaffCriteria example = new ContractorStaffCriteria();
        ContractorStaffCriteria.Criteria criteria = example.createCriteria().andDelStateEqualTo(0);
        putSearchCriteria(criteria);

        int count = contractorStaffService.countByCriteria(example);

        DataGridPagination dataGridPagination = DataGridPagination.getInstance(request, count);//获取分页对象
        PageView pageView = dataGridPagination.getPageView();//生成pageView分页对象
        //未传sort参数是采用添加时间排序
        if (StringUtils.isEmpty(sort)) {
            pageView.setSortColumn("addTime");
        } else {
            example.setOrderByClause(pageView.getSortColumn() + " " + pageView.getOrderType());
        }
        example.setPageView(pageView);

        List<ContractorStaff> contractorStaffs = contractorStaffService.selectByCriteria(example);

        return dataGridPagination.flushDataGridData(contractorStaffs);
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return MODULE_BATH_PATH + "/add";
    }

    @SystemLog(module = "承包商人员", methods = "添加承包商人员信息")
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public AjaxResult addAjax(ContractorStaff contractorStaff) {
        if (contractorStaffService.checkIfExist(contractorStaff.getContractorId(),
                contractorStaff.getCode(),
                contractorStaff.getIdcard())) {
            return fail("承包商下已存在相同工号或相同身份证号的数据！");
        }
        contractorStaff.setId(IDGenerator.getId());
        contractorStaff.setAddUserId(getSessionUser().getId());
        contractorStaff.setAddDeptId(getSessionUser().getDepartment().getId());
        contractorStaff.setAddTime(DateTimeUtil.formatterDateTime());
        if (contractorStaffService.insertSelective(contractorStaff) > 0) {
            return success("保存成功！", contractorStaff);
        } else {
            return fail("保存失败！");
        }
    }

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, String id) {
        model.addAttribute("contractorStaff", contractorStaffService.selectByPrimaryKey(id));
        return MODULE_BATH_PATH + "/edit";
    }

    @SystemLog(module = "承包商人员", methods = "编辑承包商人员信息")
    @ResponseBody
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public AjaxResult editAjax(ContractorStaff contractorStaff) throws Exception {
        String nowTime = DateTimeUtil.formatterDateTime();
        contractorStaff.setUpdateTime(nowTime);
        contractorStaff.setUpdateUserId(getSessionUser().getId());
        contractorStaff.setUpdateDeptId(getSessionUser().getDepartment().getId());
        if (contractorStaffService.updateByPrimaryKeySelective(contractorStaff) > 0) {
            return success("承包商人员信息更新成功！");
        } else {
            return fail("承包商人员信息更新失败！");
        }
    }

    @SystemLog(module = "承包商人员", methods = "删除承包商人员信息")
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public AjaxResult deleteAjax(String id) throws Exception {
        if (contractorStaffService.deleteByPrimaryKey(id) > 0) {
            return success("删除承包商人员信息成功！");
        } else {
            return fail("删除承包商人员信息失败！");
        }
    }

    @RequestMapping(value = "/toggle", method = RequestMethod.GET)
    public String toggle() {
        return MODULE_BATH_PATH + "/toggle";
    }

    @SystemLog(module = "承包商人员", methods = "启停用承包商人员")
    @ResponseBody
    @RequestMapping(value = "/toggle", method = RequestMethod.POST)
    public AjaxResult toggleAjax(String id, Integer useState, String toggleReason) throws Exception {
        ContractorStaff contractorStaff = new ContractorStaff();
        contractorStaff.setId(id);
        contractorStaff.setUseState(useState);
        contractorStaff.setToggleReason(toggleReason);
        contractorStaff.setToggleTime(DateTimeUtil.formatterDateTime());
        contractorStaff.setToggleUserId(getSessionUser().getId());
        if (contractorStaffService.updateByPrimaryKeySelective(contractorStaff) > 0) {
            if (useState == 1) {
                return success("启用成功！");
            } else {
                return success("停用成功！");
            }
        }
        return fail("操作失败");

    }

    @RequestMapping(value = "/simpleList", method = RequestMethod.GET)
    public String simpleList() {
        return MODULE_BATH_PATH + "/simpleList";
    }

    /**
     * 添加查询条件
     *
     * @param criteria 条件
     */
    private void putSearchCriteria(ContractorStaffCriteria.Criteria criteria) {
        if (StringUtils.isNotEmpty(getPara("name"))) {
            criteria.andNameLike("%" + getPara("name") + "%");
        }
        if (StringUtils.isNotEmpty(getPara("contractorName"))) {
            List<String> contractorIds = contractorInfoService.selectContractorIdsByName(getPara("contractorName"));
            if (contractorIds.isEmpty()) {
                criteria.andIdIsNull();
            } else {
                criteria.andContractorIdIn(contractorIds);
            }
        }
        if (StringUtils.isNotEmpty(getPara("contractorId"))) {
            criteria.andContractorIdEqualTo(getPara("contractorId"));
        }
        if (StringUtils.isNotEmpty(getPara("code"))) {
            criteria.andCodeEqualTo(getPara("code"));
        }
        if (StringUtils.isNotEmpty(getPara("idcard"))) {
            criteria.andIdcardEqualTo(getPara("idcard"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMin"))) {
            criteria.andAddTimeGreaterThanOrEqualTo(getPara("addTimeMin"));
        }
        if (StringUtils.isNotEmpty(getPara("addTimeMax"))) {
            criteria.andAddTimeLessThanOrEqualTo(getPara("addTimeMax"));
        }
        if (StringUtils.isNotEmpty(getPara("addUserId"))) {
            criteria.andAddUserIdEqualTo(getPara("addUserId"));
        }
        if (StringUtils.isNotEmpty(getPara("addDeptId"))) {
            criteria.andAddDeptIdEqualTo(getPara("addDeptId"));
        }
        List<String> deptIds = dataAuthorityService.selectDataDeptIdByUserIdAndDeptId(getSessionUser().getId()
                , getSessionUser().getDepartment().getId());
        if (!deptIds.isEmpty()) {
            criteria.andAddDeptIdIn(deptIds);
        }
    }
}
